<?php

require('PaypalIPN.php');

$ipn = new PayPalIPN();
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
    $txn_type = $_POST['txn_type'];
    if (strcmp($txn_type, "cart") != 0) {
        error_log("txn_type is not cart!");
    } else {
        /*
         * https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
         */
        $payment_success = 1;
        $payment_fail = 2;

        $digest = "";
        $delimiter = "___";
        $total_price = $_POST['mc_gross'];
        $oid = $_POST['invoice'];
        $currency_code = $_POST['mc_currency'];
        $merchant_email = $_POST['receiver_email'];
        $digest = $currency_code . $delimiter . $merchant_email . $delimiter;

        include_once("db_connection.php");
        $conn = getdb();
        $stmt = $conn->prepare("SELECT  *  FROM orders WHERE oid = :oid");
        $stmt->bindParam(':oid', $oid);
        $stmt->execute();
        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $order = $stmt->fetch();

        $salt = $order['salt'];
        $db_digest = $order['digest'];
        $product_number = $order['pnumber'];
        $cart_details = array();
        for ($i = 1; $i <= $product_number; $i++) {
            $item_name = $_POST['item_name' . $i];
            $item_pid = $_POST['item_number' . $i];
            $item_quantity = $_POST['quantity' . $i];
            $item_gross = $_POST['mc_gross_' . $i];

            $digest .= ($item_pid . $delimiter . $item_name . $delimiter . $item_quantity . $delimiter . number_format($item_gross, 2) . $delimiter);

            $detail = array("quantity" => $item_quantity, "price" => ($item_gross / $item_quantity), "name" => $item_name);
            $cart_details[$item_pid] = $detail;
        }

        $digest .= number_format($total_price, 2);

        $digest_hash = hash_hmac("sha256", $digest, $salt);

        $txn_id = $_POST['txn_id'];

        if (strcmp($db_digest, $digest_hash) == 0) {
            error_log("Valid digest!");

            $stmt = $conn->prepare("Update orders Set txn_id=:txn_id, payment_status=:payment_status WHERE oid = :oid And txn_id IS NULL");
            $stmt->bindParam(':oid', $oid);
            $stmt->bindParam(':txn_id', $txn_id);
            $stmt->bindParam(':payment_status', $payment_success);
            $stmt->execute();

            $count = $stmt->rowCount();
            if ($count > 0) {
                $stmt = $conn->prepare("INSERT INTO cart_item (iid , oid, pid, pname, quantity, price) VALUES (NULL,:oid, :pid, :pname, :quantity, :price)");

                foreach ($cart_details as $pid => $detail) {
                    $stmt->bindParam(':oid', $oid);
                    $stmt->bindParam(':pid', $pid);
                    $stmt->bindParam(':pname', $detail['name']);
                    $stmt->bindParam(':quantity', $detail['quantity']);
                    $stmt->bindParam(':price', $detail['price']);
                    $stmt->execute();
                }

            } else {
                error_log("Duplicated txn_id !");
            }

        } else {
            error_log("digest not valid!");
            error_log("\ndb_digest " . $db_digest . " ;digest_hash " . $digest_hash . " \n");

            $stmt = $conn->prepare("Update orders Set txn_id=:txn_id, payment_status=:payment_status WHERE oid = :oid And txn_id IS NULL");
            $stmt->bindParam(':oid', $oid);
            $stmt->bindParam(':txn_id', $txn_id);
            $stmt->bindParam(':payment_status', $payment_fail);
            $stmt->execute();
        }
    }
    //error_log(print_r($_POST, true));
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");